/**
 * Created by baby520 on 2016/8/12.
 */
define(function(require, exports, modules) {
    'use strict';

    require('css!assets/css/records/records.css');
    require('assets/plugins/md5.js');
    require('http://static.geetest.com/static/tools/gt.js');	//极客SDK

    var template = require('text!./records.html'),
        deal4=require('text!./deal-4.html'),
        deal3=require('text!./deal-3.html'),
        deal2=require('text!./deal-2.html'),
        deal1=require('text!./deal-1.html'),wait,
        ad=require('text!../farm/ad.html'),
        util = require('util');
    var View = Backbone.View.extend({
        el : '#page',
        events : {
        	'click .header_box' : function(){
        		this.show_shade('modifyUserInfo');
        		$('.modifyUserInfo input[name="weixin"]').val('');
        		$('.modifyUserInfo input[name="zhifubao"]').val('');
        	},
        	'click #confirmModifyUserInfo': 'confirmModifyUserInfo',
        	'click #btn-activate' : function(){
        		this.show_shade('activate');
        		$('.activate input[name="upperUserRefId"]').val('');
        		$('.activate input[name="phone"]').val('');
        	},
        	'click #confirmActivate': 'confirmActivate',
        	'click .common-loading' : function(){
        		$(".common-loading,.gt").remove();
        	},
            'click #inside':function () {
                loadingShow();
                var inside=document.getElementById("inside");
                var side=document.getElementById("side");
               
                    var transFlag=0;
                    if(inside.className=='open2'){
                        transFlag=1
                    }
                    jsonpGet(util.NDNserver+"/setTransFlag",{token: this.token,
                        userId:this.userId,transFlag:transFlag},"setTransFlag",$.proxy(function(res){
                        console.log(res)
                        loadingRemove();
                        if(res.code==1){
                            side.className=(side.className=="close1")?"open1":"close1";
                            inside.className=(inside.className=="close2")?"open2":"close2";
                        }
                    },this));

            },
            'click .btn_sendConfirm':function (event) {
                var giftId=$(event.currentTarget).data('id');
                var _this=this;
                loadingShow();
                //出售确认
                jsonpGet(util.NDNserver+"/sendConfirm",{token: this.token,
                    userId:this.userId,giftId:giftId},"sendConfirm",$.proxy(function(res){
                    console.log(res)
                    loadingRemove();
                    if(res.code==1){
                        _this.getData(_this.currentPage,_this.deal_type)
                    }else{
                        _this.show_shade('error');
                        $('.shade .error p').text(res.msg)
                    }
                },this));
            },
            'click .btn_receiveConfirm':function (event) {
                var giftId=$(event.currentTarget).data('id');
                var _this=this;
                loadingShow();
                //购买确认
                jsonpGet(util.NDNserver+"/receiveConfirm",{token: this.token,
                    userId:this.userId,giftId:giftId},"receiveConfirm",$.proxy(function(res){
                    console.log(res)
                    loadingRemove();
                    if(res.code==1){
                        _this.getData(_this.currentPage,_this.deal_type)
                    }else{
                        _this.show_shade('error');
                        $('.shade .error p').text(res.msg)
                    }
                },this));
            },
            'click .shade .error>.yellowBtn':'hide_shade',
            'click .shade .register':'hide_shade',
            'click .lower':function () {
                
                this.currentPage++;
                if(this.currentPage>this.totalSize){
                    this.currentPage=this.totalSize;
                    return;
                }
                this.getData(this.currentPage,this.deal_type);
            },
            'click .upper':function () {
                this.currentPage--;
                if(this.currentPage<1){
                    this.currentPage=1;
                    return;
                }
                this.getData(this.currentPage,this.deal_type);
            },
            'click #to_yes':function () {
                var validation=$('.validation').val();
                if(validation){
                    this.confirmTransaction(validation);

                }

            },
            'click #to_not':'hide_shade',
            'click #yanzhengcode':function (event) {
                var $elm=$(event.currentTarget);
                if($elm.hasClass('sended')){
                    return;
                }
                this.sendVerifyCode($elm);


            },
            'click #confirm1':function () {
                var _this=this;
                var phone='',password='',password2='',gender=1,upperLoginName='',userName='',loginName='',registeUserId='';
                var weixin = '',zhifubao='';
                phone=$.trim($('input[name="phone"]').val());
                password=$.trim($('input[name="password"]').val());
                password2=$.trim($('input[name="password2"]').val());
                loginName=$.trim($('input[name="loginName"]').val());
                userName=$.trim($('input[name="userName"]').val());
                weixin=$.trim($('input[name="weixin"]').val());
                zhifubao=$.trim($('input[name="zhifubao"]').val());
                upperLoginName=$.trim($('input[name="upperLoginName"]').val());
                $('input[name="sex"]').each(function(index,item){
                    if($(item).attr('checked')){
                        gender=$(item).val();
                    }
                })
                if(loginName.length>12){
                    return;
                }
                if(userName.length>12){
                    return;
                }
                if(_.isEmpty(phone)){
                    return;
                }
                if(phone=='' || userName===''
                || upperLoginName=='' || loginName==''){
                    return;
                }
                var parm = {
                		phone: phone,
                		loginName: loginName,
                		userName: userName,
                		weixin: weixin,
                		zhifubao: zhifubao,
                		upperLoginName: upperLoginName,
                		gender: gender,
                		registeUserId: this.userId
                };
                loadingShow();
    			$('body').append('<div class="gt"></div>');
    			var handlerPopupMobile = function (captchaObj) {
    		        // 将验证码加到id为captcha的元素里
    		        captchaObj.appendTo(".gt");
    		        //拖动验证成功后两秒(可自行设置时间)自动发生跳转等行为
    		        captchaObj.onSuccess(function () {
    		        	$(".gt").remove();
    		            var validate = captchaObj.getValidate();
    		            jsonpGet(
    	            		util.NDNserver + "/userRegister", // 进行二次验证
    		                {
    		                    // 二次验证所需的三个值
    	            			token: _this.token,
    	            			jsonStr: JSON.stringify(parm),
    		                    geetest_challenge: validate.geetest_challenge,
    		                    geetest_validate: validate.geetest_validate,
    		                    geetest_seccode: validate.geetest_seccode
    		                },
    		                'userRegister',
    		                function (res) {
    		                	$(".common-loading").remove();
    		                	if(res.code==1){
    		                        $('.package').html(deal1);
    		                        _this.show_shade('register');
    		                    }else{
    		                        _this.show_shade('error');
    		                        $('.shade .error p').text(res.msg)
    		                    }
    		                }
    		            );
    		        });
    		        // 更多接口参考：http://www.geetest.com/install/sections/idx-client-sdk.html
    		    };
    		    jsonpGet(
    		        // 获取id，challenge，success（是否启用failback）
    		        util.NDNserver + "/geetestRegister", 
    		        {t: new Date().getTime()},	// 加随机数防止缓存
    		        'geetestRegister',
    		        function (json) {
    		            // 使用initGeetest接口
    		            // 参数1：配置参数
    		            // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
    		        	var data = $.parseJSON(json.data);
    		            initGeetest({
    		                gt: data.gt,
    		                challenge: data.challenge,
    		                offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
    		                // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
    		            }, handlerPopupMobile);
    		        }
    		    );

            },
            'click #confirm2':function () {
                var inside=document.getElementById("inside");
                var type=1;
                if(inside){
                    if(inside.className=="open2"){
                        type=0
                    }else{
                        type=1;
                    }
                }
                $('.validation').val('');
                wait=60;
                var _this=this;
                var friendName='',friendLoginName='',eggNum='',userId='',chickenNum='';
                friendLoginName=$.trim($('input[name="friendLoginName"]').val());
                userId=this.userId;
                friendName=$.trim($('input[name="friendName"]').val());
                var obj='{"friendName":"'+friendName+'","friendLoginName":"'+
                    friendLoginName+'","userId":"'+userId+'","type":"'+type;

                if(this.type=="eggNum"){
                    eggNum=$.trim($('input[name="eggNum"]').val());
                    if(eggNum==''){
                        this.show_shade('error');
                        $('.shade .error p').text('请填写鸡蛋数量');
                        return;
                    }
                    if(eggNum%10!=0){
                        this.show_shade('error');
                        $('.shade .error p').text('出售数量必须是10的倍数');
                        return
                    }
                    obj+='","eggNum":"'+eggNum+'"}';
                }else{
                    chickenNum=$.trim($('input[name="chickenNum"]').val());
                    if(chickenNum==''){
                        this.show_shade('error');
                        $('.shade .error p').text('请填写小鸡的数量');
                        return;
                    }
                    if(chickenNum%10!=0){
                        this.show_shade('error');
                        $('.shade .error p').text('出售数量必须是10的倍数');
                        return
                    }
                    obj+='","chickenNum":"'+chickenNum+'"}';
                }

                if(friendName==''){
                    this.show_shade('error');
                    $('.shade .error p').text('请填写姓名');
                    return;
                }
                if(friendLoginName==''){
                    this.show_shade('error');
                    $('.shade .error p').text('请填写用户名');
                    return;
                }
                loadingShow();
    			$('body').append('<div class="gt"></div>');
    			var handlerPopupMobile = function (captchaObj) {
    		        // 将验证码加到id为captcha的元素里
    		        captchaObj.appendTo(".gt");
    		        //拖动验证成功后两秒(可自行设置时间)自动发生跳转等行为
    		        captchaObj.onSuccess(function () {
    		        	$(".gt").remove();
    		            var validate = captchaObj.getValidate();
    		            jsonpGet(
    	            		util.NDNserver + "/userTransaction", // 进行二次验证
    		                {
    		                    // 二次验证所需的三个值
    	            			token: _this.token,
    	            			jsonStr: obj,
    		                    geetest_challenge: validate.geetest_challenge,
    		                    geetest_validate: validate.geetest_validate,
    		                    geetest_seccode: validate.geetest_seccode
    		                },
    		                'userTransaction',
    		                function (res) {
    		                	$(".common-loading").remove();
    		                	if(res.code==1){
    		                        _this.show_shade('sell');
    		                        var $elm=$('#yanzhengcode');
    		                        _this.time($elm);
    		                        _this.actionId=res.data;
    		                    }else{
    		                        _this.show_shade('error');
    		                        $('.shade .error p').text(res.msg)
    		                    }
    		                }
    		            );
    		        });
    		        // 更多接口参考：http://www.geetest.com/install/sections/idx-client-sdk.html
    		    };
    		    jsonpGet(
    		        // 获取id，challenge，success（是否启用failback）
    		        util.NDNserver + "/geetestRegister", 
    		        {t: new Date().getTime()},	// 加随机数防止缓存
    		        'geetestRegister',
    		        function (json) {
    		            // 使用initGeetest接口
    		            // 参数1：配置参数
    		            // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
    		        	var data = $.parseJSON(json.data);
    		            initGeetest({
    		                gt: data.gt,
    		                challenge: data.challenge,
    		                offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
    		                // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
    		            }, handlerPopupMobile);
    		        }
    		    );
            },
            'click .black_1':function () {
                Backbone.history.navigate('home',{trigger:true});
            },
            'click nav .box div':function (event) {
               /* $(event.currentTarget).addClass('keep');
                $(event.currentTarget).siblings().removeClass('keep');*/
                if($(event.currentTarget).data('tab')==1){
                    this.currentPage=1;
                    this.deal_type=2
                    this.getData(this.currentPage,this.deal_type)
                }else{
                    this.currentPage=1;
                    this.deal_type=1
                    this.getData(this.currentPage,this.deal_type)
                }

            },
            'click .left-sd ul li':function(event){
                event.preventDefault();
                var _this=this;
                var _self=event.currentTarget;
                var tab=$(_self).attr('data-tab');
                $(_self).removeClass('nth-give'+tab);
                $(_self).addClass('nth'+tab);
               if(tab==1){
                   $('.package').html(deal1);
               }else if(tab==2){
                   this.type="eggNum";
                   this.deal2=_.template(deal2);
                   loadingShow();
                   jsonpGet(util.NDNserver+"/getTransFlag",{
                           token:_this.token,
                           userId:_this.userId},
                       "getTransFlag",$.proxy(function(res){
                           console.log(res)
                           loadingRemove();
                           if(res.code==1){
                               $('.package').html(_this.deal2({is_enable:res.data}));
                               _this.queryMyStore(_this.type);
                           }

                       },this));

               }else if(tab==3){
                   this.type="chickenNum";
                   _this.deal3=_.template(deal3);
                   loadingShow();
                   jsonpGet(util.NDNserver+"/getTransFlag",{
                       token:_this.token,
                       userId:_this.userId,},
                       "getTransFlag",$.proxy(function(res){
                           console.log(res)
                       loadingRemove();
                       if(res.code==1){
                           $('.package').html(_this.deal3({is_enable:res.data}));
                           _this.queryMyStore(_this.type);
                       }
                   },this));

               }else if(tab==4){
                   this.currentPage=1;
                   this.deal_type=1
                   this.getData(this.currentPage,this.deal_type)
               }

                $('.left-sd ul li').each(function(i,item){
                    var index=i;
                    index++;
                    if(!$(item).hasClass('nth-give'+index)){
                        if(tab!=index){
                            $(item).addClass('nth-give'+index);

                        }
                        /*if($('li:not("'+_self+'")')){*/

                        /*}*/
                    }
                })
            },
            'click .radio-btn':function (event) {
                event.preventDefault();
                if(!$(event.currentTarget).hasClass('checkedRadio')){
                    $(event.currentTarget).addClass('checkedRadio');
                    $(event.currentTarget).find('input[type=radio]').attr("checked",true);
                    $(event.currentTarget).siblings().removeClass('checkedRadio');
/*                    $(event.currentTarget).siblings('.radio-btn').find('input[type=radio]').removeAttr('checked')*/
                    $(event.currentTarget).siblings('.radio-btn').find('input[type=radio]').attr('checked',function(){
                        return false;
                    })
                }

            }
        },
        confirmTransaction:function (vCode) {
            var _this=this;
            loadingShow();
            jsonpGet(util.NDNserver+"/confirmTransaction",{
                token:this.token,
                userId:this.userId,
                actionId:_this.actionId,vCode:vCode},"confirmTransaction",$.proxy(function(res){
                loadingRemove();
                if(res.code==1){
                    if(this.type=='eggNum'){
                        _this.deal2=_.template(deal2);
                        loadingShow();
                        jsonpGet(util.NDNserver+"/getTransFlag",{
                                token:_this.token,
                                userId:_this.userId,},
                            "getTransFlag",$.proxy(function(res){
                                console.log(res)
                                loadingRemove();
                                if(res.code==1){
                                    $('.package').html(_this.deal2({is_enable:res.data}));
                                    _this.queryMyStore(_this.type);
                                }

                            },this));
                    }else{
                        _this.deal3=_.template(deal3);
                        loadingShow();
                        jsonpGet(util.NDNserver+"/getTransFlag",{
                                token:_this.token,
                                userId:_this.userId,},
                            "getTransFlag",$.proxy(function(res){
                                console.log(res)
                                loadingRemove();
                                if(res.code==1){
                                    $('.package').html(_this.deal3({is_enable:res.data}));
                                    _this.queryMyStore(_this.type);
                                }

                            },this));

                    }
                    _this.show_shade('error');
                    $('.shade .error p').text('出售成功');
                    _this.queryMyStore(this.type);
                }else{
                    _this.show_shade('error');
                    $('.shade .error p').text(res.msg);
                }
            },this));
        },
        queryMyStore:function(type){
            loadingShow();
            var _this = this;
            jsonpGet(util.NDNserver+'/queryMyStore',{userId:  this.user.userId,token:  this.user.token,status:'1'},'queryMyStore',$.proxy(function(json){
                console.log(json)
                loadingRemove();
                if(json.code == '1'){
                    var data = json.data;
                    _this.eggNum=data.eggsNum;
                    _this.chicksNum=data.chicksNum;
                    if(type=='eggNum'){
                        $('#forms .feasible-num').text(data.eggsNum);
                    }else{
                        $('#forms .feasible-num').text(data.chicksNum);
                    }
                }else{
                    _this.show_shade('error');
                    $('.shade .error p').text(json.msg)
                }
                
            },this));
        },

        //验证码
        sendVerifyCode:function (el) {
            var _this=this;
            loadingShow();
            jsonpGet(util.server+"/getTranVcode",{
                userId:this.userId,token:this.token,
                actionId:_this.actionId},"getTranVcode",$.proxy(function(res){
                console.log(res)
                loadingRemove();
                if(res.code==1){
                    this.time(el);
                }else{
                    _this.show_shade('error');
                    $('.shade .error p').text(res.msg)
                }
            },this));
        },
        time:function(o){
            var _this=this;
            if (wait == 0) {
                $("#yanzhengcode").removeClass('sended');
                o.attr('disabled',false).text('获取验证码');
                wait = 60;
            } else {
                /*o.setAttribute("disabled", true);*/
               $("#yanzhengcode").addClass('sended'); //
                o.attr('disabled',true).text('重新发送( '+ wait + ')');
                wait--;
                setTimeout(function() {
                        _this.time(o)
                    },
                    1000)
            }
        },
        hide_shade: function () {
            $('.shade').hide(0);
            $('section.shade >div').hide(0);
        },
        show_shade: function (ele) {

            $('section.shade').show(0);
            $('section.shade >div').hide(0);
            $('section.shade > .'+ele).show(0);
        },
        item:function(){
            var item='<section class="shade">'+
                '<div class="content min confirm sell">'+
                '<div class="flex-box">'+
                '<div class="f-l"></div>'+
                '<div class="flex"></div>'+
                '<div class="f-r"></div>'+
                '</div><p>确认出售</p> <label  for=""> ' +
                '<input type="number" class="validation" value=""> <button style="width: 5.2rem;right: 0.4rem;left: auto;" id="yanzhengcode" class="codeV yellowBtn">获取验证码</button></label> <br>'+
                '<button class="buffBtn" id="to_not"><span>取消</span></button>'+
                '<button class="yellowBtn" id="to_yes"><span>确认</span></button>'+
                '<i class="bottom"></i>'+
                '</div>'+
                '</section>';

            return item;
        },
        getData:function (currentPage,type) {
            loadingShow();
            var _this=this;
            jsonpGet(util.NDNserver+"/getUserTrasRecord",{
                userId:this.userId,
                token:this.token,
                type:type,currentPage:currentPage,numPerPage:7},"getUserTrasRecord",$.proxy(function(res){
               loadingRemove();
                if(res.code==1){
                    this.totalSize=res.data.pageCount;
                    var data=res.data.recordList;
                    _.each(data,function(obj,index){
                      /*  if(obj['daily']){
                            obj['daily']=_this.daily(obj['daily']);
                        }else{
                            obj['daily']=formatDate(new Date(obj['createTime']),3);
                        }*/
                        obj['daily']=formatDate(new Date(obj['createTime']),3);
                    })
                    _this.deal4=_.template(deal4);
                    $('.package').html(_this.deal4({data:res.data,type:type}));
                }else{
                    _this.show_shade('error');
                    $('.shade .error p').text(res.msg)
                }
            },this));
        },
        initialize : function() {
            this.eggNum=0;
            this.chicksNum=0;
            this.user=JSON.parse(util.getCookie('user'));
			if(!this.user){
				Backbone.history.navigate('loading',{trigger:true});
				return;
			}
			if(this.user.userStatus == 3){
				Backbone.history.navigate('home',{trigger:true});
				return;
			}
            this.token=this.user.token;
            this.userId=this.user.userId;
            this.currentPage=1;
            this.actionId=0;
            this.deal_type=1
            wait=60;
            this.template = _.template(template);
            this.render();
            $('.package').html(deal1);
            $('.deal header .header-name .header_box').css({'background-image': this.user.userPic && this.user.userPic.length>0 ? "url('"+this.user.userPic+"')" : "url('assets/images/home/portrait/portrait-man.png')"});
            $('.deal header .header-name .leaf').text(this.user.loginName||"")

            //this.getData(this.currentPage,this.deal_type);
            this.pageSetting();
            //$('.package').html(deal4);

        },
        pageSetting:function(){
        	function setSection (){
				var userAgent = navigator.userAgent.toLowerCase();
				var mobile = userAgent.match(/(iphone|ipod|android|ios|ipad)/i);
				var isPC = !mobile;
				if(isPC){
					$('section.shade').width($('#page').width()).css({'margin': 'auto','left': 'initial'});
				}
			};
			window.onresize = function () { setSection ();};
			$(document).ready(function(){ setSection ();});
        },
        render : function() {
            this.$el.html(this.template());

        },
        confirmActivate: function(){
        	var upperUserRefId = $.trim($('section .activate input[name="upperUserRefId"]').val());
        	var phone = $.trim($('section .activate input[name="phone"]').val());
        	if(!phone || !upperUserRefId){
        		return;
        	}
        	var _this = this;
        	loadingShow();
			$('body').append('<div class="gt"></div>');
			var handlerPopupMobile = function (captchaObj) {
		        captchaObj.appendTo(".gt");
		        captchaObj.onSuccess(function () {
		        	$(".gt").remove();
		            var validate = captchaObj.getValidate();
		            jsonpGet(
	            		util.NDNserver + "/userActive", // 进行二次验证
		                {
	            			token: _this.token,
	            			userId: _this.userId,
	            			userRefId: upperUserRefId,
	            			phone: phone,
		                    geetest_challenge: validate.geetest_challenge,
		                    geetest_validate: validate.geetest_validate,
		                    geetest_seccode: validate.geetest_seccode
		                },
		                'userActive',
		                function (res) {
		                	$(".common-loading").remove();
		                	if(res.code==1){
		                        _this.hide_shade();
		                        commonAlert_oneBtn('激活成功');
		                    }else{
		                        _this.show_shade('error');
		                        $('.shade .error p').text(res.msg);
		                    }
		                }
		            );
		        });
		    };
		    jsonpGet(
		        util.NDNserver + "/geetestRegister", 
		        {t: new Date().getTime()},	// 加随机数防止缓存
		        'geetestRegister',
		        function (json) {
		        	var data = $.parseJSON(json.data);
		            initGeetest({
		                gt: data.gt,
		                challenge: data.challenge,
		                offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
		            }, handlerPopupMobile);
		        }
		    );
        	
        },
        confirmModifyUserInfo: function(){
        	var weixin = $.trim($('.modifyUserInfo input[name="weixin"]').val()),
        		zhifubao = $.trim($('.modifyUserInfo input[name="zhifubao"]').val());
        	var parm = {
    			userId: this.userId,
	        	token: this.token,
	        	weixin: weixin,
	        	zhifubao: zhifubao
        	};
        	if(!weixin && !zhifubao){
        		return;
        	}
        	jsonpGet(
		        util.server + "/updatePlayerInfo",
		        parm,
		        'updatePlayerInfo',
		        $.proxy(function (json) {
		        	if(json.code == 1){
		        		this.hide_shade();
		        		commonAlert_oneBtn('修改成功');
		        	}
		        },this));
        }
    });

    return View;
});